import { defineStore } from 'pinia'
import { useAccountStore, useFollowStore } from '@/store'
import { fmtEmail, fmtMobile } from '@/utils'
import { getProfile } from '@/api/profile'
import {
	BindingTabType,
	FollowShowType,
	NoticeDialogInfo,
	ProfileDialogInfo,
	SettingsShowEnum,
	UserInfo
} from '@/types'
import { ViewType } from '@/views/profile/profile/types.ts'

export const useProfileStore = defineStore('profile', {
	state: () => ({
		userInfo: null as UserInfo | null,
		profileAccountShow: false,
		profileShow: null as ProfileDialogInfo | null,
		isShowBindingPopup: false,
		bindingTabShow: BindingTabType.email,
		noticeShow: null as NoticeDialogInfo | null,
		reportShow: false,
		show: {
			email: false,
			mobile: false,
			baseInfo: false,
			identity: false,
			enable2fa: false,
			disable2fa: false,
			updatePassword: false
		} as Record<SettingsShowEnum, boolean>
	}),
	actions: {
		setReportShow(val: boolean) {
			this.reportShow = val
		},
		setBindingTab(type: any) {
			this.bindingTabShow = type
		},
		setBindingPopupShow(val: boolean) {
			this.isShowBindingPopup = val
		},
		setUserInfo(data: UserInfo) {
			this.userInfo = data
		},
		patchUserInfo(data: Partial<UserInfo>) {
			if (this.userInfo) {
				this.userInfo = { ...this.userInfo, ...data }
			}
		},
		async getUserInfo() {
			try {
				const { data } = await getProfile()
				this.setUserInfo(data)
			} catch (error) {
				console.error(error)
			}
		},
		async clearUserInfo() {
			this.userInfo = null
		},
		showProfileAccount(val: boolean) {
			this.profileAccountShow = val
		},
		showProfile(val: ProfileDialogInfo) {
			if (val.show) {
				const followStore = useFollowStore()
				if (this.profileShow?.show && followStore.followShow?.show) {
					followStore.showFollow({
						show: false,
						userId: undefined,
						userName: undefined,
						type: FollowShowType.none,
						nickName: undefined
					})
				}
			}
			this.profileShow = { viewType: ViewType.main, userId: this.userInfo?.userId, ...val }
		},
		showProfileType(type: ViewType) {
			if (this.profileShow) this.profileShow.viewType = type
		},
		hideProfile() {
			this.profileShow = { ...this.profileShow, show: false }
		},
		showNotice(val: NoticeDialogInfo) {
			this.noticeShow = val
		}
	},
	getters: {
		email: (state) => fmtEmail(state.userInfo?.email),
		mobile: (state) =>
			fmtMobile(`${state.userInfo?.internationalAreaCode} ${state.userInfo?.mobile}`),
		lockWallet: (state) => {
			if (state.userInfo) {
				if (!state.userInfo.emailVerify && !state.userInfo.mobileVerify) {
					if (state.userInfo.email) {
						return 'email'
					} else if (state.userInfo.mobile) {
						return 'mobile'
					}
				}
			}
			return false
		},
		isMe: (state) => {
			const accountStore = useAccountStore()
			return (id: string | number | undefined) =>
				accountStore.isLogin && (!id || state.userInfo?.userId === +id)
		}
	},
	persist: true
})
